﻿namespace TestTool.GUI.Utils
{
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Linq;
    using TestTool.GUI.Data;
    using TestTool.GUI.Properties;
    using TestTool.Tests.Definitions.Data;
    using TestTool.Tests.Definitions.Enums;
    using TestTool.Tests.Definitions.Interfaces;
    using TestTool.Tests.Definitions.Trace;

    internal class DoCGenerator : PdfReportGenerator
    {
        private const string FeatureListAccompanied = "This Declaration of Conformance MUST be accompanied by the Feature List generated by the ONVIF Device Test Tool";
        private const string FirstParagraphText = "This Declaration of Conformance is issued by the indicated Member which is solely responsible for declared conformance. Conformance  is valid ONLY for the device identified when used in a manner consistent with the intent of the referenced documents.";
        private const string OnvifLogoText = "Driving IP-based physical security through global standardization";
        private const string TestReportAccompanied = "This Declaration of Conformance MUST be accompanied by the Test Report  generated by the ONVIF Device Test Tool";
        private const string Title = "Declaration  of Conformance – Device";

        private void AddAutorizationTable(Document document)
        {
            int count = 0x3b;
            Dictionary<string, string> rows = new Dictionary<string, string>();
            rows.Add("Signature:", new string('_', count));
            rows.Add("Name:", new string('_', count));
            rows.Add("Title and department:", new string('_', count));
            rows.Add("Date:", new string('_', count));
            PdfPTable element = this.CreateReportTable(rows, "Signature of Authorized Representative:", FontFactory.GetFont("Arial", (float)10f), null, null);
            element.SetWidthPercentage(new float[] { document.PageSize.Width * 0.25f, document.PageSize.Width * 0.75f }, document.PageSize);
            document.Add(element);
            Paragraph paragraph = this.CreateParagraph("This Declaration of Conformance MUST be accompanied by the Feature List generated by the ONVIF Device Test Tool", FontFactory.GetFont("Arial", (float)9f), 3);
            document.Add(paragraph);
        }

        private void AddDeviceTable(Document document, TestLogFull data)
        {
            string[] strArray = new string[] { string.Format("PTZ:   {0}", ((data.Features != null) && data.Features.Contains(Feature.PTZService)) ? "Yes" : "NO"), string.Format("Audio: {0}", ((data.Features != null) && data.Features.Contains(Feature.Audio)) ? "Yes" : "NO"), string.Format("I/O:   {0}", ((data.Features != null) && data.Features.Contains(Feature.DeviceIORelayOutputs)) ? "Yes" : "NO") };
            Dictionary<string, string> rows = new Dictionary<string, string>();
            rows.Add("Product name:", data.ProductName);
            rows.Add("Product firmware version:", data.DeviceInformation.FirmwareVersion);
            rows.Add("Device features:", string.Join(Environment.NewLine, strArray));
            PdfPTable element = this.CreateReportTable(rows, "Device:", FontFactory.GetFont("Arial", (float)10f), null, null);
            element.SetWidthPercentage(new float[] { document.PageSize.Width * 0.32f, document.PageSize.Width * 0.68f }, document.PageSize);
            document.Add(element);
        }

        private void AddResponsibleMethodTable(Document document, TestLogFull data)
        {
            Dictionary<string, string> rows = new Dictionary<string, string>();
            rows.Add("Member name:", data.MemberInfo.Name);
            rows.Add("Member address", data.MemberInfo.Address);
            PdfPTable element = this.CreateReportTable(rows, "Responsible member:", FontFactory.GetFont("Arial", (float)10f), null, null);
            element.SetWidthPercentage(new float[] { document.PageSize.Width * 0.25f, document.PageSize.Width * 0.75f }, document.PageSize);
            document.Add(element);
        }

        private void AddSpecificationsTable(Document document, TestLogFull data)
        {
            int count = 0x35;
            int num2 = Enumerable.Count<KeyValuePair<TestInfo, TestResult>>(data.TestResults, (Func<KeyValuePair<TestInfo, TestResult>, bool>)(item => (item.Value.Log.TestStatus == TestStatus.Failed)));
            Func<IProfileDefinition, bool> CachedAnonymousMethodDelegate5 = null;
            if ((num2 <= 0) && (CachedAnonymousMethodDelegate5 == null))
            {
                CachedAnonymousMethodDelegate5 = P => P.Status == ProfileVersionStatus.Release;
            }
            bool flag = ((Enumerable.Where<IProfileDefinition>(data.InitializationData.FailedProfiles, CachedAnonymousMethodDelegate5).Count<IProfileDefinition>() > 0) || (data.InitializationData.SupportedProfiles.Count == 0)) || (base.Log.InitializationData.UndefinedFeatures.Count > 0);
            Dictionary<string, string> rows = new Dictionary<string, string>();
            Func<IProfileDefinition, bool> CachedAnonymousMethodDelegate6 = null;
            if (!flag && (CachedAnonymousMethodDelegate6 == null))
            {
                CachedAnonymousMethodDelegate6 = P => P.Status == ProfileVersionStatus.Release;
            }

            Func<IProfileDefinition, string> CachedAnonymousMethodDelegate7 = null;
            rows.Add("Profile:", (CachedAnonymousMethodDelegate7 != null) ? new string('_', count) : string.Join("; ", Enumerable.Select<IProfileDefinition, string>(Enumerable.Where<IProfileDefinition>(data.InitializationData.SupportedProfiles, CachedAnonymousMethodDelegate6), CachedAnonymousMethodDelegate7).ToArray<string>()));
            rows.Add("ONVIF Device Test Tool version:", data.Application.ToolVersion);
            if (flag)
            {
                rows.Add("Tool test result:", string.Format("FAILED TEST CASES: {0} ", num2));
                rows.Add("Applicable Test Tool errata:", new string('_', count));
            }
            PdfPTable element = this.CreateReportTable(rows, "The device identified above conforms to the following specifications:", FontFactory.GetFont("Arial", (float)10f), flag ? "This Declaration of Conformance MUST be accompanied by the Test Report  generated by the ONVIF Device Test Tool" : null, flag ? FontFactory.GetFont("Arial", (float)9f) : null);
            element.SetWidthPercentage(new float[] { document.PageSize.Width * 0.32f, document.PageSize.Width * 0.68f }, document.PageSize);
            document.Add(element);
        }

        private Paragraph CreateParagraph(string text, iTextSharp.text.Font font, int align)
        {
            return new Paragraph(text, font) { Alignment = align };
        }

        private PdfPTable CreateReportTable(Dictionary<string, string> rows, string title, iTextSharp.text.Font font, string foother, iTextSharp.text.Font footherFont)
        {
            PdfPTable table = new PdfPTable(2)
            {
                HorizontalAlignment = 0
            };
            PdfPCell cell = new PdfPCell(this.CreateParagraph(title + Environment.NewLine, FontFactory.GetFont("Arial", (float)10f), 0))
            {
                Colspan = 2,
                BorderWidth = 0f
            };
            table.AddCell(cell);
            for (int i = 0; i < rows.Count; i++)
            {
                PdfPCell cell2 = new PdfPCell(new Phrase(rows.ElementAt<KeyValuePair<string, string>>(i).Key, font));
                PdfPCell cell3 = new PdfPCell(new Phrase(rows.ElementAt<KeyValuePair<string, string>>(i).Value, font));
                cell2.Padding = 5f;
                cell2.PaddingTop = 8f;
                cell2.PaddingBottom = 8f;
                cell3.Padding = 5f;
                cell3.PaddingTop = 8f;
                cell3.PaddingBottom = 8f;
                if (i > 0)
                {
                    cell2.BorderWidthTop = 0f;
                    cell3.BorderWidthTop = 0f;
                }
                if ((i < (rows.Count - 1)) || !string.IsNullOrEmpty(foother))
                {
                    cell2.BorderWidthBottom = 0f;
                    cell3.BorderWidthBottom = 0f;
                }
                cell2.BorderWidthRight = 0f;
                cell3.BorderWidthLeft = 0f;
                table.AddCell(cell2);
                table.AddCell(cell3);
            }
            if (!string.IsNullOrEmpty(foother))
            {
                PdfPCell cell4 = new PdfPCell(new Phrase(foother, footherFont ?? font))
                {
                    Colspan = 2,
                    HorizontalAlignment = 0,
                    BorderWidthTop = 0f,
                    Padding = 5f,
                    PaddingTop = 8f
                };
                table.AddCell(cell4);
            }
            table.ElementComplete = true;
            return table;
        }

        protected override void CustomDocumentInitialization()
        {
            base.Document.SetMargins(50f, 50f, 80f, 50f);
            base.Writer.PageEvent = this.InitializeCustomPageEventHandler();
        }

        protected override void GenerateDocumentContent()
        {
            this.GeneratePage(base.Document, base.Log);
        }

        private void GeneratePage(Document document, TestLogFull data)
        {
            Paragraph element = this.CreateParagraph(Environment.NewLine, FontFactory.GetFont("Times-Bold", (float)10f), 1);
            Paragraph paragraph2 = this.CreateParagraph("Declaration  of Conformance – Device", FontFactory.GetFont("Times-Bold", (float)14f), 1);
            document.Add(paragraph2);
            document.Add(element);
            Paragraph paragraph3 = this.CreateParagraph("This Declaration of Conformance is issued by the indicated Member which is solely responsible for declared conformance. Conformance  is valid ONLY for the device identified when used in a manner consistent with the intent of the referenced documents.", FontFactory.GetFont("Arial", (float)10f), 3);
            document.Add(paragraph3);
            document.Add(element);
            this.AddResponsibleMethodTable(document, data);
            document.Add(element);
            this.AddDeviceTable(document, data);
            document.Add(element);
            this.AddSpecificationsTable(document, data);
            document.Add(element);
            this.AddAutorizationTable(document);
        }

        private iTextSharp.text.Image GetPdfImage(Bitmap image)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                image.Save(stream, ImageFormat.Bmp);
                stream.Position = 0L;
                return iTextSharp.text.Image.GetInstance(stream);
            }
        }

        private CustomPageEventHelper InitializeCustomPageEventHandler()
        {
            return new CustomPageEventHelper { HeaderLogo = this.GetPdfImage(Resources.OnvifLogo), HeaderText = "Driving IP-based physical security through global standardization", HeaderFont = FontFactory.GetFont("Arial Narrow", 8f, iTextSharp.text.Color.GRAY), FooterFont = FontFactory.GetFont("Arial", 10f, iTextSharp.text.Color.GRAY), FootherFirst = "ONVIF", FootherSecond = "www.onvif.org", FootherThird = "info@onvif.org" };
        }
    }
}

